import React, { memo, useState, useEffect } from 'react';
import { useNavigate, useLocation } from 'react-router-dom';
import { Menu, MenuValue } from 'tdesign-react';
import router, { IRouter } from 'router';
import { resolve } from 'utils/path';
import { useAppSelector } from 'modules/store';
import { selectGlobal } from 'modules/global';
import MenuLogo from './MenuLogo';
import Style from './Menu.module.less';
import buyIcon from 'assets/layout/menus/buy.png';
import operationIcon from 'assets/layout/menus/operation.png';
import useManageIcon from 'assets/layout/menus/useManage.png';
import userIcon from 'assets/layout/menus/user.png';
import { useDispatch, useSelector } from 'react-redux';
import { addTag } from 'modules/layout/tags';

const icons = {
  user: userIcon,
  buy: buyIcon,
  operation: operationIcon,
  useManage: useManageIcon,
};

const { SubMenu, MenuItem, HeadMenu } = Menu;

interface IMenuProps {
  showLogo?: boolean;
  showOperation?: boolean;
}

const renderMenuItems = (menu: IRouter[], parentPath = '', expandedKeys: string[] = []) => {
  const navigate = useNavigate();
  const dispatch = useDispatch();
  const tags = useSelector((state: any) => state.tags.tags);

  const handleClickMenu = (path: string, title: string) => {
    const item = tags.find((item: any) => item.path === path);
    if (!item) {
      dispatch(addTag({ label: title, path }));
    }
    navigate(path);
  };
  return menu.map((item) => {
    const { children, meta, path } = item;

    if (!meta || meta?.hidden === true) {
      // 无meta信息 或 hidden == true，路由不显示为菜单
      return null;
    }

    const { icon, title, single } = meta;
    const routerPath = resolve(parentPath, path);

    if (!children || children.length === 0) {
      return (
        <MenuItem
          key={routerPath}
          value={routerPath}
          // icon={Icon ? <Icon /> : undefined}
          onClick={() => {
            handleClickMenu(routerPath, title ?? '');
          }}
        >
          {title}
        </MenuItem>
      );
    }

    if (single && children?.length > 0) {
      const firstChild = children[0];
      if (firstChild?.meta && !firstChild?.meta?.hidden) {
        const { Icon, title } = meta;
        const singlePath = resolve(resolve(parentPath, path), firstChild.path);
        return (
          <MenuItem
            key={singlePath}
            value={singlePath}
            icon={Icon ? <Icon /> : undefined}
            onClick={() => navigate(singlePath)}
          >
            {title}
          </MenuItem>
        );
      }
    }

    return (
      <SubMenu
        key={routerPath}
        value={routerPath}
        title={<span style={{ paddingLeft: '10px' }}>{title}</span>}
        icon={
          icon && icons[icon as keyof typeof icons] ? (
            <img width={20} height={20} src={icons[icon as keyof typeof icons]} />
          ) : undefined
        }
      >
        {renderMenuItems(children, routerPath)}
      </SubMenu>
    );
  });
};

/**
 * 顶部菜单
 */
export const HeaderMenu = memo(() => {
  const globalState = useAppSelector(selectGlobal);
  const location = useLocation();
  const [active, setActive] = useState<MenuValue>(location.pathname);
  const [expandedKeys, setExpandedKeys] = useState<string[]>([]);

  // 监听 location 变化，更新展开状态
  useEffect(() => {
    // 可根据路由路径自动展开对应菜单
    const pathParts = location.pathname.split('/').filter(Boolean);
    const keysToExpand: string[] = [];
    let currentPath = '';

    pathParts.forEach((part) => {
      currentPath += `/${part}`;
      keysToExpand.push(currentPath);
    });

    setExpandedKeys(keysToExpand);
  }, [location.pathname]);

  return (
    <HeadMenu
      expandType='popup'
      style={{ marginBottom: 20 }}
      value={active}
      theme={globalState.theme}
      onChange={(v) => setActive(v)}
      expanded={expandedKeys}
      onExpand={(keys) => setExpandedKeys(keys as string[])}
    >
      {renderMenuItems(router, '', expandedKeys)}
    </HeadMenu>
  );
});

// 修改左侧菜单组件
export default memo((props: IMenuProps) => {
  const location = useLocation();
  const globalState = useAppSelector(selectGlobal);
  const [expandedKeys, setExpandedKeys] = useState<string[]>([]);

  const { version } = globalState;
  const bottomText = globalState.collapsed ? version : `IPPeak Admin System`;

  // 获取第一个有效的菜单路径
  const getFirstValidMenuPath = (menus: IRouter[], parentPath = ''): string | null => {
    for (const menu of menus) {
      // 跳过隐藏的菜单项
      if (!menu.meta || menu.meta.hidden === true) continue;

      const currentPath = resolve(parentPath, menu.path);

      // 如果有子菜单，递归查找
      if (menu.children && menu.children.length > 0) {
        const childPath = getFirstValidMenuPath(menu.children, currentPath);
        if (childPath) {
          return childPath;
        }
      }
      // 如果是叶子节点且有路径，则返回该路径
      else if (menu.path) {
        return currentPath;
      }
    }
    return null;
  };

  // 监听 location 变化，更新展开状态
  useEffect(() => {
    // 根据当前路由路径自动展开对应菜单
    const pathParts = location.pathname.split('/').filter(Boolean);
    const keysToExpand: string[] = [];
    let currentPath = '';

    pathParts.forEach((part) => {
      currentPath += `/${part}`;
      keysToExpand.push(currentPath);
    });

    setExpandedKeys(keysToExpand);
  }, [location.pathname]);

  // 初始化时展开第一个菜单项
  useEffect(() => {
    // 只有在还没有展开任何菜单时才设置默认展开项
    if (expandedKeys.length === 0) {
      const firstPath = getFirstValidMenuPath(router);
      if (firstPath) {
        // 构建需要展开的所有父级路径
        const pathSegments = firstPath.split('/').filter(Boolean);
        const pathsToExpand: string[] = [];
        let accumulatedPath = '';

        pathSegments.forEach((segment) => {
          accumulatedPath += `/${segment}`;
          pathsToExpand.push(accumulatedPath);
        });

        setExpandedKeys(pathsToExpand);
      }
    }
  }, []); // 仅在组件挂载时执行一次

  return (
    <Menu
      width='232px'
      style={{ flexShrink: 0, height: '100%' }}
      className={Style.menuPanel2}
      value={location.pathname}
      theme={globalState.theme}
      collapsed={globalState.collapsed}
      operations={props.showOperation ? <div className={Style.menuTip}>{bottomText}</div> : undefined}
      logo={props.showLogo ? <MenuLogo collapsed={globalState.collapsed} /> : undefined}
      expanded={expandedKeys}
      onExpand={(keys) => setExpandedKeys(keys as string[])}
    >
      {renderMenuItems(router, '', expandedKeys)}
    </Menu>
  );
});
